/*
 * @Descripttion: 出手鸭小程序
 * @version:1.0.1 
 * @Author: HHL
 * @Date: 2022-11-16 17:51:59
 * @LastEditTime: 2025-07-03 09:39:01
 * @LastEditors: sueRimn
 */

import store from '@/store'
import {
  BASEHOST, appid, platform, partnerId, appKey
} from '@/config'
import { waitShowToast, mapToStr, setExpData, getExpData } from '../utils'
import { generateSignature, getSignedParams } from '@/utils/signature'

// #ifndef H5
const accountInfo = {miniProgram:{}}
// const accountInfo = uni.getAccountInfoSync()
// #endif

// 强制登录页面
const checkLoginPages = [
  'pages/assess/index',
  'pages/done/index',
  'pages/coupon/index',
  'pages/commonweal/list/index',
  'pages/commonweal/select/index',
  'pages/dataSecurity/list/index',
  'pages/order/index',
  'pages/order/info',
]

const _request = async (opts) => {
  const { url, data, header } = opts
  // let storageDataKey = url.replace(BASEHOST,"").replace(/\//g, ".") + "" +
  // mapToStr(data).toLocaleLowerCase();
  // if (header.cache_maxage) {
  //   let storageData = getExpData(storageDataKey);
  //   if (storageData) {
  //     uni.hideLoading()
  //     // return storageData;
  //   }
  // }
  try {

    const [err, res] = await uni.request(opts)
    // console.log("请求结果", res)
    // console.log("请求参数", err)
    // token过期
    if (res.data && res.data.code === 401) {
      const pages = getCurrentPages()
      const page = pages[pages.length - 1]
      const { route, $page } = page

      // 退出登录
      store.dispatch('user/onLogout')



      // #ifdef H5
      if (checkLoginPages.indexOf(route) === -1) {
        uni.reLaunch({ url: `/pages/login/index?to_from=${$page.fullPath}` })
      }
      // #endif

      // 强制跳转登录页面
      // #ifndef H5
      const index = checkLoginPages.findIndex(item => $page.fullPath.indexOf(item) !== -1)
      if (index !== -1) {
        uni.reLaunch({ url: `/pages/auth/index?to_from=${$page.fullPath}` })
      }
      // #endif
    }

    if (
      res.data && (res.data.code === 400 ||
        res.data.code === 500 ||
        res.data.code === -1)
    ) {
      uni.hideLoading()
      console.log("请求错误", res.data.msg)
      waitShowToast(res.data.msg || "网络错误～")
      return res.data
    }
    if (res.data) {
      uni.hideLoading()
      // if (opts.method == "GET" && res.data.code == 200 && opts.header.cache_maxage) {
      //   setExpData(storageDataKey, res.data, opts.header.cache_maxage)
      // }
      return res.data
    }

    // 请求错误
    uni.showToast({
      title: res.data.msg || "网络错误～",
      icon: 'none'
    })

  } catch (error) {
    console.error("请求异常", error)
    uni.showToast({ title: error.msg || "网络错误～", icon: 'none' })
    return {
      code: -9527,
      data: '',
    }
  }
}

// 请求公共参数
const publicParams = {
  platform,
  appId: appid
}


function Request() {
  function request(opts) {
    const timestamp = Date.now();
    const data = opts.data || {};
    const signedData = generateSignature({
      ...publicParams,
      ...data
    }, timestamp, appKey, "md5");
    return _request({
      ...opts,
      header: {
        'platform': platform,
        'timestamp': timestamp,
        'sign': signedData,
        'appid': appid,
        'partnerId':partnerId,
        // #ifndef H5
        'version': accountInfo.miniProgram.version, // 线上小程序版本号
        'env_version': accountInfo.miniProgram.envVersion, // 小程序当前运行版本
        // #endif

        'Authorization': getApp().globalData.token || '',

        ...opts.header,
      }
    })
  }

  return {
    get(url, data, header = {}) {
      return request({
        url: url,
        method: 'GET',
        header,
        data: {
          ...publicParams,
          ...data,
        },
      });
    },
    post(url, data, header = {}) {
      Object.assign(header, { 'content-type': 'application/json' })
      return request({
        url: url,
        method: 'POST',
        header,
        data: {
          ...publicParams,
          ...data,
        },
      })
    },
    put(url, data, header = {}) {
      Object.assign(header, { 'content-type': 'application/json' })
      return request({
        url: url,
        method: 'PUT',
        header,
        data: {
          ...publicParams,
          ...data,
        },
      })
    },
    postForm(url, data, header = {}) {
      Object.assign(header, { 'content-type': 'application/x-www-form-urlencoded' })
      return request({
        url: url,
        method: 'POST',
        header,
        data: {
          ...publicParams,
          ...data,
        },
      })
    },
    del(url, data) {
      return request({
        url: url,
        method: 'DELETE',
        data: {
          ...publicParams,
          ...data,
        },
      })
    },
  }
}

export default Request()